import React, { ReactNode } from 'react';
// eslint-disable-next-line import/no-extraneous-dependencies
import { withRouter } from 'react-router-dom';
import { connect } from 'dva';
import { Modal, Form, Table, Input, Upload, Icon, message } from 'antd';
import Cookies from 'js-cookie';
import { FormattedMessage, formatMessage } from 'umi-plugin-react/locale';

import { getCreateColumns, getRelationColumns } from '../utils';
import { UPLOAD_PIC, CACHE_TOKEN, CACHE_UID, SUCCESS_CODE } from '../../data';
import styles from '../style.less';
import { getOrderInfo, getWithdrawBankList } from '../../service';
import { uploadImgHttp, handleSendData } from '@/utils/tools';

const { TextArea } = Input;
const FormItem = Form.Item;
const { Dragger } = Upload;

interface StateType {
  [propName: string]: any;
}

interface PropType {
  [propName: string]: any;
}

class CreateDetailDialog extends React.PureComponent<PropType, StateType> {
  public state = {
    uploadApi: `${UPLOAD_PIC}?token=${Cookies.get(CACHE_TOKEN)}&uid=${Cookies.get(CACHE_UID)}`,
    fileList: [],
    fileListLength: 0,
    uploadCount: 0,
    isUpload: false,
    previewVisible: false,
    previewImage: '',
    inputOrderId: undefined, // 创建订单-关联订单号
    inputAmount: 0, // 创建订单-订单金额
    orderInfo: {
      recharge: {
        orderId: undefined,
        amount: undefined,
        username: undefined,
        channelId: undefined,
      },
    }, // 订单信息
    bankList: [], // 银行卡列表
    files: '', // 图片地址
  };

  componentDidMount(): void {
    // 监听剪切板
    document.addEventListener('paste', this.handleCopyImg);
  }

  componentWillUnmount(): void {
    document.removeEventListener('paste', this.handleCopyImg);
  }

  private handleCopyImg = (event: any) => {
    const { files } = this.state;
    const items = event.clipboardData && event.clipboardData.items;
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    let file = null;
    if (items && items.length) {
      // 检索剪切板items
      // eslint-disable-next-line no-plusplus
      for (let i = 0; i < items.length; i++) {
        if (items[i].type.indexOf('image') !== -1) {
          file = items[i].getAsFile();
          break;
        }
      }
    }
    this.setState({ isUpload: true });
    uploadImgHttp(this.state.uploadApi, file, (imgStr: string) => {
      this.setState({ isUpload: false, files: `${files ? `${files},` : ''}${imgStr}` });
    });
  };

  // 查看图片详情
  private handleImg = (index: number) => {
    const { files } = this.state;
    const list = files.split(',');
    this.setState({
      previewImage: list[index],
      previewVisible: true,
    });
  };

  // 删除图片
  private imgDelete = (index: number) => {
    const { files } = this.state;
    const arr = files.split(',');
    arr.splice(index, 1);
    this.setState({
      files: arr.join(','),
    });
  };

  // 获取订单详情
  private getInfo = (): void => {
    getOrderInfo({ orderId: this.state.inputOrderId }).then(({ code, data }: any) => {
      if (code === SUCCESS_CODE && data) {
        this.setState({ orderInfo: data });
        const { channelId } = data.recharge;
        if (channelId) this.getBankList({ channelId });
      }
    });
  };

  // 获取银行卡
  private getBankList = (params: object): void => {
    getWithdrawBankList(params).then(({ code, data }: any) => {
      if (code === SUCCESS_CODE && data) {
        this.setState({ bankList: data });
      }
    });
  };

  // 提交
  private handleSubmit = () => {
    const {
      orderInfo: { recharge },
      isUpload,
      files,
      inputAmount,
      inputOrderId,
    } = this.state;
    if (isUpload) {
      // 图片上传中，请稍后再试！
      message.error(formatMessage({ id: 'recharge-logs.img-uploading-warning' }));
      return;
    }
    this.props.form.validateFields((err: any, values: any) => {
      if (!err) {
        const tableSaveData = {
          relationOrderId: inputOrderId,
          amount: inputAmount,
        };
        const { channelId } = recharge;
        const isStorm = channelId === 1001 || channelId === 1003;
        this.props.confirm(
          handleSendData({ ...values, ...tableSaveData, attachments: files }),
          isStorm,
        );
      }
    });
  };

  // 确认按钮是否可用
  okBtnAvailable = () => {
    const { fileList, orderInfo } = this.state;
    const { orderId, amount } = orderInfo.recharge;
    this.props.form.validateFields((err: any, values: any) => {
      if (!err && fileList.length > 0 && orderId && amount) {
        return true;
      }
      return false;
    });
  };

  // 渲染截图
  private renderImgList = (): ReactNode => {
    const { files } = this.state;
    const fileList = files.split(',');

    return fileList.length ? (
      <ul className={styles.imgViewContianer}>
        {fileList.map((item: any, index: number) => {
          const ele = item ? (
            <li key={item}>
              <Icon
                type="close-circle"
                className={styles.closeIcon}
                onClick={() => {
                  this.imgDelete(index);
                }}
              />
              <img
                src={item}
                alt=""
                style={{ width: '100%', height: '100%' }}
                onClick={() => {
                  this.handleImg(index);
                }}
              />
            </li>
          ) : null;
          return ele;
        })}
      </ul>
    ) : null;
  };

  // 渲染表格
  private renderTable = (): ReactNode => {
    const { orderInfo, bankList } = this.state;
    const { recharge } = orderInfo;
    const obj = {
      paymentId: undefined,
      channelName: undefined,
      merchantCode: undefined,
      cardUsername: undefined,
      bankName: undefined,
      ...recharge,
    };
    const data = [
      {
        paymentId: obj.paymentId || '',
        channelName: obj.channelName || '',
        merchantCode: obj.merchantCode || '',
        cardUsername: obj.cardUsername || '',
        bankName: obj.bankName || '',
        username: obj.username || '',
        amount: 0,
        payeeName: '',
        payeeBankId: '',
      },
    ];

    return (
      <Table
        className={styles.tableContainer}
        size="small"
        bordered
        rowKey={(record: any, index: number) => String(index)}
        columns={getCreateColumns(this, bankList, this.getInfo)}
        dataSource={data}
        pagination={false}
      />
    );
  };

  // 关联订单号表格
  private renderRelationTable = () => {
    const { recharge } = this.state.orderInfo;
    const valueList = Object.values(recharge);
    const list = valueList.filter(item => !!item);
    const data = list.length > 0 ? [recharge] : [];

    return (
      <Table
        style={{ wordBreak: 'break-all' }}
        className={styles.tableContainer}
        size="small"
        bordered
        rowKey={(record: any, index: number) => String(index)}
        columns={getRelationColumns()}
        dataSource={data}
        pagination={false}
      />
    );
  };

  private onSuccess = (info: any) => {
    const { code, data, message: msg } = info;
    const { uploadCount, files, fileListLength } = this.state;
    if (code === SUCCESS_CODE) {
      const list = files ? files.split(',') : [];
      if (list.length >= 3) return;

      const arr = list.length ? [...list, data] : [data];
      const str = arr.join(',');

      if (arr.length >= 3 || uploadCount === fileListLength - 1) {
        this.setState({
          isUpload: false,
          files: str,
          uploadCount: 0,
          fileListLength: 0,
        });
        return;
      }
      this.setState({
        uploadCount: uploadCount + 1,
        files: str,
      });
    } else {
      message.error(msg);
    }
  };

  private beforeUpload = (file: any, fileList: any) => {
    const { length } = fileList;
    this.setState({
      isUpload: true,
      fileListLength: length,
    });
    return true;
  };

  render() {
    const self = this;
    const { visible } = this.props;
    const { getFieldDecorator } = this.props.form;
    const {
      uploadApi,
      previewVisible,
      previewImage,
      isUpload,
      files,
      inputAmount,
      inputOrderId,
    } = this.state;
    const remark = this.props.form.getFieldValue('remark');
    const imgList = files.split(',').filter(item => !!item);
    const okBtnAvailable = remark && inputOrderId && inputAmount && imgList.length > 0 && !isUpload;

    const props = {
      name: 'file',
      multiple: true,
      action: uploadApi,
      accept: 'image/*',
      showUploadList: false,
      onSuccess: self.onSuccess,
      beforeUpload: self.beforeUpload,
    };

    return (
      <Modal
        visible={visible}
        width={1200}
        title={formatMessage({ id: 'recharge-logs.modal-title' })}
        onCancel={this.props.cancle}
        onOk={this.handleSubmit}
        okButtonProps={{ disabled: !okBtnAvailable }}
        okText={formatMessage({ id: 'recharge-logs.create-btn' })}
        cancelText={formatMessage({ id: 'recharge-logs.cancel-btn' })}
      >
        {this.renderTable()}
        <h4 style={{ marginTop: '10px' }}>关联订单号详情</h4>
        {this.renderRelationTable()}
        <Form>
          {/* 备注 */}
          <FormItem label={<FormattedMessage id="recharge-logs.form-remark" />}>
            {getFieldDecorator('remark', {
              initialValue: '',
              rules: [
                {
                  required: true,
                  message: formatMessage({
                    id: 'recharge-logs.form-remark-required',
                  }),
                },
              ],
            })(<TextArea rows={4} />)}
          </FormItem>
        </Form>

        <h4>
          {/* 上传转账凭证截图： */}
          <span className={styles.tip}>*</span>
          {formatMessage({ id: 'recharge-logs.img-upload-title' })}
        </h4>

        {imgList.length !== 3 ? (
          <Dragger {...props}>
            <p className="ant-upload-drag-icon">
              <Icon type="inbox" />
            </p>
            <p className="ant-upload-text">拖拽图片、或点击图片上传</p>
          </Dragger>
        ) : null}
        {this.renderImgList()}
        {isUpload ? <p>{formatMessage({ id: 'recharge-logs.img-upload-status' })}...</p> : null}

        <Modal
          width={1200}
          visible={previewVisible}
          footer={null}
          onCancel={() => {
            this.setState({ previewVisible: false });
          }}
        >
          <img alt="" style={{ width: '100%' }} src={previewImage} />
        </Modal>
      </Modal>
    );
  }
}

const CreateDetailDialogContainer = Form.create({ name: 'createDialog' })(CreateDetailDialog);

export default withRouter(
  connect(({ recharge }: { recharge: any }) => ({
    recharge,
  }))(CreateDetailDialogContainer),
);
